package studiodiva.portfolio.client.lib.view;

import static com.google.gwt.query.client.GQuery.$;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptException;
import com.google.gwt.dom.client.Style.Position;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.query.client.css.CSS;
import com.google.gwt.query.client.css.Length;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.SimplePanel;


import static studiodiva.portfolio.client.lib.lang.Lang.doLater;

public class EditableHTML extends View<FlowPanel> {
  private DialogBox dialog;
  private CkEditor editor;
  private final HTML html = new HTML();

  public EditableHTML() {
    initWidget(new FlowPanel());
    if (!GWT.isProdMode()) ensureAttached(this, new Runnable() {
      public void run() {
        initializeEditMode();
      }
    });
    widget().add(html);
  }

  public void setHTML(String value) {
    html.setHTML(value);
  }

  private void initializeEditMode() {
    CkEditor.initialize();
    Button editButton = new Button("edit");
    widget().add(editButton);
    $(asWidget()).css(CSS.POSITION.with(Position.RELATIVE));
    $(editButton).css(CSS.POSITION.with(Position.ABSOLUTE));
    $(editButton).css(CSS.RIGHT.with(Length.px(0)));
    $(editButton).css(CSS.TOP.with(Length.px(0)));
    editButton.addClickHandler(new ClickHandler() {
      @Override
      public void onClick(ClickEvent event) {
        onEditPressed();
      }
    });
  }

  private void onEditPressed() {
    dialog = new DialogBox(true) {
      @Override
      public void hide(boolean autoClosed) {
        editor.close();
        widget().add(html);
        super.hide(autoClosed);
      }
    };
    dialog.addCloseHandler(new CloseHandler<PopupPanel>() {
      public void onClose(CloseEvent<PopupPanel> event) {

        try {

        } catch (JavaScriptException e) {}
      }
    });
    SimplePanel dialogContent = new SimplePanel();
    dialogContent.setWidget(html);
    dialog.setWidget(dialogContent);
    dialog.setPopupPosition(-3000, -3000);
    dialog.show();
    editor = new CkEditor(html);
    doLater(500, new Runnable() {
      @Override
      public void run() {
        dialog.center();
      }
    });
  }
}
